﻿#include "recentfiles.h"
#include "global_define.h"
#include <QDebug>

recentFiles::recentFiles(QWidget *parent) :
    QMenu(parent)
{
    actionItem = QList<QAction*>();
    setting_config = new QSettings(INICONFIG, QSettings::IniFormat, 0);
    setting_config->setIniCodec("GB2312");

    initMenu();

    connect(this,SIGNAL(openRecentFile(QString)),
            FindTopParent<MainWindow *>(this),SLOT(FileOpen_slot(QString)));
}

recentFiles::~recentFiles()
{

}

void recentFiles::initMenu()
{
    QStringList recentList;
    recentList = setting_config->value("LASTOPEN").value<QStringList>();

    foreach (const QString &itemText, recentList) {
        actionItem << new QAction(itemText, this);
        addAction(actionItem.last());
    }

    foreach (const QAction *itemAction, actionItem) {
        connect(itemAction,&QAction::triggered,[=]{
            //qDebug()<<itemAction->text();
            emit openRecentFile(itemAction->text());
        });
    }

    addSeparator();
    clearRecent = new QAction(tr("清除最近打开列表"),this);
    addAction(clearRecent);
    connect(clearRecent,&QAction::triggered,[=]{
        while(!actionItem.isEmpty()){
            delete(actionItem.takeAt(0));
        }
        QStringList empty;
        empty.clear();
        setting_config->setValue("LASTOPEN",empty);
//        qDebug()<<"clearRecent"<<actionItem;
    });
}

void recentFiles::reloadList(QStringList)
{
    while(!actionItem.isEmpty()){
        delete(actionItem.takeAt(0));
    }
    delete(clearRecent);
    initMenu();
}
